import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import axios from '@/http/axios'
import Login from '@/views/Login'
import Home from '@/views/Home'
import Welcome from '@/views/Home/Welcome'
import NotFound from '@/views/Error/404'

import Index from '@/views/Index/List'
import Article from '@/views/Index/Article'

Vue.use(Router)

let welcome = { path: '', component: Welcome, name: '系统介绍' }
const router = new Router({
  routes: [
    {
      path: '/admin',
      component: Home,
      children: [welcome]
    },
    {
      path: '/',
      name: '首页',
      component: Index
    },
    {
      path: '/label/:id',
      name: '分类列表',
      component: Index
    },
    {
      path: '/article/:id',
      name: '博文',
      component: Article
    },
    {
      path: '/login',
      name: '登录',
      component: Login
    },
    {
      path: '*',
      name: 'notFound',
      component: NotFound
    }
  ]
})

router.beforeEach((to, from, next) => {
  loadConfig()
  if (to.path === '/login' || to.path === '/' || to.path.search('/label/') === 0 || to.path.search('/article/') === 0) {
    next()
  } else {
    // 如果访问非前台界面或登录界面，且户会话信息不存在，代表未登录，则跳转到登录界面
    let user = store.state.app.user
    if (user.id === undefined) {
      next({ path: '/login' })
    } else {
      let loading = loadDynamicRoutes()
      if (loading) {
        // 加载路由后需重新跳转
        let path = to.path
        if (path.search('/login') === 0) {
          path = '/admin'
        }
        console.log('跳转到:', path)
        next({ path: path })
      } else {
        next()
      }
    }
  }
})

/**
 * 加载配置信息
 */
function loadConfig () {
  if (store.state.app.configLoading) {
    return
  }
  store.commit('configLoading', true)
  axios({
    url: '/getConfig',
    method: 'get'
  }).then((res) => {
    if (res.code === 0) {
      store.commit('loadConfig', res.data)
    }
  })
}

/**
* 加载动态路由
*/
function loadDynamicRoutes () {
  if (store.state.app.menuRouteLoaded) {
    return false
  }
  // 添加动态路由
  let dynamicRoutes = addDynamicRoutes(store.state.app.routers, [welcome])
  router.options.routes[0].children = dynamicRoutes
  router.matcher = new Router({ mode: 'hash' }).matcher
  router.addRoutes(router.options.routes)
  // 保存加载状态
  store.commit('menuRouteLoaded', true)
  console.log('加载动态路由...')
  return true
}

/**
* 添加动态(菜单)路由
*/
function addDynamicRoutes (routerList = [], routes = []) {
  routerList.forEach(item => {
    let url = item.url.replace(/^\//, '')
    let path = getPath(url)
    let id = item.id
    if (item.catalog === 'B') {
      id = item.parentId
    }
    // 创建路由配置
    var route = {
      path: item.url,
      component: resolve => require([`@/views/${path}`], resolve),
      name: item.label,
      meta: {
        id: id,
        title: item.label
      }
    }
    routes.push(route)
  })
  return routes
}

function getPath (url) {
  let array = url.split('/')
  let path = ''
  array.forEach(item => {
    path += item.substring(0, 1).toUpperCase() + item.substring(1) + '/'
  })
  return path.substring(0, path.length - 1)
}
export default router
